<template>
  <div class="tempbigbox">
    <!-- 左边整体内容模块 -->
    <div class="console">
      <div class="column column2">
        <!-- <ActiveUser></ActiveUser>
          <SalesOverview></SalesOverview> -->
        <div class="page-content">
          <h3 style="margin-bottom: 20px">推广商品</h3>
          <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick" style="margin-top: 20px">
            <el-tab-pane label="学员班型" name="0"> </el-tab-pane>
            <el-tab-pane label="会员卡权益" name="1"> </el-tab-pane>
          </el-tabs>
          <el-form :model="searchForm" ref="searchFormRef" label-width="auto" style="margin-top: 20px">
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item :label="activeName === '0' ? '班型名称：' : '会员卡信息：'" prop="productName">
                  <el-input v-model="searchForm.productName" @blur="getData"
                    :placeholder="activeName === '0' ? '请输入班型名称' : '请输入会员卡信息'" clearable />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- <el-button style="margin-top: 20px" @click="getData">搜索</el-button>
            <el-button style="margin-top: 20px" @click="reset">重置</el-button> -->
            <el-button style="margin-top: 20px" @click="showDialog">
              {{ activeName === '0' ? '新增班型' : '新增会员卡' }}
            </el-button>
          </el-form>
          <art-table :data="tableData" selection :currentPage="pageNum" :pageSize="pageSize" :total="pagetotal"
            @current-change="currentChange" @size-change="sizeChange">
            <template #default>
              <el-table-column :label="activeName === '0' ? '班型信息' : '会员卡信息'" prop="avatar" #default="scope"
                width="300px">
                <div class="user" style="display: flex; align-items: center">
                  <el-image v-if="scope.row.productImg" style="width: 48px; height: 48px" preview-teleported
                    :preview-src-list="[scope.row.productImg]" hide-on-click-modal
                    :src="scope.row.productImg"></el-image>
                  <div>
                    <p class="user-name">{{ scope.row.productName }}</p>
                    <p class="email">{{ scope.row.productPrice }}</p>
                  </div>
                </div>
              </el-table-column>
              <el-table-column label="状态" prop="status" #default="scope" align="center">
                <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"></el-switch>
              </el-table-column>
              <el-table-column label="比例规则" prop="brokerageRule" align="center">
                <template #default="scope">
                  {{ scope.row.brokerageRule === 0 ? '跟随等级' : '独立规则' }}
                </template>
              </el-table-column>
              <el-table-column label="商品佣金比例" align="center">
                <template #default="scope">
                  <el-dropdown trigger="click">
                    <span class="el-dropdown-link">
                      <span v-if="scope.row.levelDetailsAos && scope.row.levelDetailsAos.length">
                        {{
                          (() => {
                            const { min, max } = getPercentRange(
                              scope.row.levelDetailsAos,
                              'firstPercent'
                            )
                            return min === max ? `${min}%` : `${min}% ~ ${max}%`
                          })()
                        }}
                      </span>
                      <el-icon class="el-icon--right"
                        v-if="scope.row.levelDetailsAos && scope.row.levelDetailsAos.length"><arrow-down /></el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item v-for="(item, index) in scope.row.levelDetailsAos" :key="index">{{
                          `${item.levelName}：${item.firstPercent / 100}%` }}</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </template>
              </el-table-column>
              <el-table-column label="邀请人奖励比例" align="center">
                <template #default="scope">
                  <el-dropdown trigger="click">
                    <span class="el-dropdown-link">
                      <span v-if="scope.row.levelDetailsAos && scope.row.levelDetailsAos.length">
                        {{
                          (() => {
                            const { min, max } = getPercentRange(
                              scope.row.levelDetailsAos,
                              'secondPercent'
                            )
                            return min === max ? `${min}%` : `${min}% ~ ${max}%`
                          })()
                        }}
                      </span>
                      <el-icon class="el-icon--right"
                        v-if="scope.row.levelDetailsAos && scope.row.levelDetailsAos.length"><arrow-down /></el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item v-for="(item, index) in scope.row.levelDetailsAos" :key="index">{{
                          `${item.levelName}：${item.secondPercent / 100}%` }}</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </template>
              </el-table-column>
              <el-table-column label="添加时间" prop="createTime" align="center" />
              <el-table-column label="推广渠道" prop="djs" align="center">
                <template #default="scope">
                  <span>微信</span>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="300px" align="center">
                <template #default="scope">
                  <button-table type="edit" @click="editRules(scope.row)" />
                  <button-table type="delete" @click="deleteUser(scope.row.productId)" />
                </template>
              </el-table-column>
            </template>
          </art-table>
          <class-type-dialog :show-question-type-visible="showClassType" v-if="showClassType"
            @close-dialog="closeSelectionDialog" :product-type="productType"></class-type-dialog>
        </div>
      </div>

      <!-- <div class="column column2">
          <NewUser></NewUser>
          <NewUser></NewUser>
        </div> -->
      <el-dialog v-model="dialogVisible" title="修改比例" width="50%" :close-on-click-modal="false">
        <el-table :data="rulesData" :span-method="tableSpanMethod">
          <el-table-column label="选择比例">
            <template #default="scope">
              <el-radio-group v-model="brokerageRule" @change="radioChange">
                <el-radio value="0" size="large">跟随等级规则</el-radio>
                <el-radio value="1" size="large">商品独立设置</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column prop="levelName" label="等级名称"></el-table-column>
          <el-table-column label="商品佣金比例" prop="firstPercent" align="center">
            <template #default="scope">
              <!-- 这里可以用el-input实现可编辑 -->
              <el-input v-model="scope.row.firstPercent" type="number" min="0" max="100" style="width: 160px"
                :disabled="brokerageRule === '0'">
                <template #append> % </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="邀请人奖励比例" prop="secondPercent" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.secondPercent" type="number" min="0" max="100" style="width: 160px"
                :disabled="brokerageRule === '0'">
                <template #append> % </template>
              </el-input>
            </template>
          </el-table-column>
        </el-table>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleSubmit">确认</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useSettingStore } from '@/store/modules/setting'
import { WEB_LINKS } from '@/utils/constants'
import { useCommon } from '@/composables/useCommon'
import { FormInstance } from 'element-plus'
import { ElMessageBox, ElMessage } from 'element-plus'
import type { FormRules } from 'element-plus'
import { promoteProducts, removeProducts, promotionLevel, updateProduct } from '@/api/marketing'
import { classType } from '@/api/userStudentsApi'
import classTypeDialog from './widget/classTypeDialog.vue'
const brokerageRule = ref('0')

const dialogVisible = ref(false)
const settingStore = useSettingStore()
const currentGlopTheme = computed(() => settingStore.systemThemeType)
const activeName = ref('0')
const productType = ref('0')
const showClassType = ref(false)
const rulesData = ref([])
const globalRulesData = ref([])
const productRulesData = ref<any>([])

const getPercentRange = (levelDetailsAos: any[], key: string) => {
  if (!Array.isArray(levelDetailsAos) || levelDetailsAos.length === 0) return { min: 0, max: 0 }
  const percents = levelDetailsAos.map((item) => Number(item[key] || 0) / 100)
  return {
    min: Math.min(...percents),
    max: Math.max(...percents)
  }
}

const closeSelectionDialog = (value: boolean) => {
  showClassType.value = false
  if (value) {
    getData()
  }
}
const handleClick = (e: any) => {
  productType.value = e
  getData()
}

// 系统主题风格变化时，刷新页面重写渲染 Echarts
watch(currentGlopTheme, () => {
  settingStore.reload()
})

useCommon().scrollToTop()

const searchForm = reactive({
  productName: ''
})

const searchFormRef = ref<FormInstance>()

const tableData = ref([])

const showDialog = () => {
  showClassType.value = true
}

const deleteUser = (productId: string) => {
  ElMessageBox.confirm('确定要移除该用户吗？', '移除用户', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    const res = await removeProducts({ productId })
    if (res.code === '00000') {
      ElMessage.success('移除成功')
      getData()
    }
  })
}

const pagetotal = ref()
const pageNum = ref(1)
const pageSize = ref(10)
const tableLoading = ref(false)

const filterEmptyValues = (obj: any) => {
  const result: any = {}
  for (const key in obj) {
    if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
      result[key] = obj[key]
    }
  }
  return result
}

async function getData() {
  try {
    tableLoading.value = true
    const params = filterEmptyValues(searchForm)
    const { code, data } = await promoteProducts({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      productType: productType.value === '0' ? 1 : 0,
      ...params
    })
    if (code === '00000') {
      tableData.value = data.list
      pagetotal.value = data.total
    }
  } catch (e) {
  } finally {
    tableLoading.value = false
  }
}
const currentChange = (val: number) => {
  pageNum.value = val
  getData()
}

const sizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getData()
}

interface Option {
  label: string
  value: string | number // 根据实际值调整
}
const classList = ref<Option[]>([])
const getClassTypeList = async () => {
  const res = await classType()
  classList.value = res.data
}
const reset = () => {
  searchForm.productName = ''
}

interface editItem {
  id: string
  productId: string
  productName: string
  productType: number
}
const editList = ref<editItem>({
  id: '',
  productId: '',
  productName: '',
  productType: 0
})
const editRules = (e: any) => {
  editList.value = e
  dialogVisible.value = true
  brokerageRule.value = String(e.brokerageRule)
  console.log(e.levelDetailsAos, 'levelDetailsAos===')
  productRulesData.value = e.levelDetailsAos
    ? e.levelDetailsAos.map((e: any) => ({
      levelName: e.levelName,
      sortOrder: e.sortOrder,
      ruleAgentCount: e.ruleAgentCount,
      ruleCustomerAmount: e.ruleCustomerAmount,
      ruleCustomerCount: e.ruleCustomerCount,
      firstPercent: e.firstPercent / 100,
      secondPercent: e.secondPercent / 100
    }))
    : []
  getRulesInfo()
}
const handleSubmit = async () => {
  console.log(productRulesData.value, 'productRulesData===')
  productRulesData.value = productRulesData.value.map((e: any) => {
    return {
      ...e,
      firstPercent: e.firstPercent * 100,
      secondPercent: e.secondPercent * 100
    }
  })
  const params = {
    id: editList.value.id,
    productId: editList.value.productId,
    productName: editList.value.productName,
    brokerageRule: Number(brokerageRule.value),
    productType: editList.value.productType,
    levelDetailsVos: productRulesData.value
  }
  const res = await updateProduct(params)
  if (res.code === '00000') {
    ElMessage.success('修改成功')
    dialogVisible.value = false
    getData()
  }
}
const radioChange = (e: any) => {
  if (e === '0') {
    rulesData.value = globalRulesData.value
  } else {
    rulesData.value = productRulesData.value
  }
}
const getRulesInfo = async () => {
  try {
    const res = await promotionLevel()
    if (res.code === '00000' && res.data) {
      globalRulesData.value = res.data.map((e: any) => ({
        ...e,
        firstPercent: e.firstPercent / 100,
        secondPercent: e.secondPercent / 100
      }))
      if (brokerageRule.value === '0') {
        rulesData.value = globalRulesData.value
      } else {
        rulesData.value = productRulesData.value
      }
    }
  } catch {
  } finally {
  }
}

const tableSpanMethod = ({
  rowIndex,
  columnIndex
}: {
  rowIndex: number
  columnIndex: number
}) => {
  // 选择比例列合并（第0列）
  if (columnIndex === 0) {
    if (rowIndex === 0) {
      return {
        rowspan: rulesData.value.length,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
}

onMounted(() => {
  getData()
  getClassTypeList()
})
</script>

<style lang="scss" scoped>
.console {
  padding-bottom: 15px;

  :deep(.card-header) {
    display: flex;
    justify-content: space-between;
    padding: 20px 25px 5px 0;

    .title {
      h4 {
        font-size: 18px;
        font-weight: 500;
        color: var(--art-text-gray-800);
      }

      p {
        margin-top: 3px;
        font-size: 13px;

        span {
          margin-left: 10px;
          color: #52c41a;
        }
      }
    }
  }

  // 主标题
  :deep(.box-title) {
    color: var(--art-gray-900) !important;
  }

  // 副标题
  :deep(.subtitle) {
    color: var(--art-gray-600) !important;
  }

  :deep(.card-list li),
  .region,
  .dynamic,
  .bottom-wrap {
    background: var(--art-main-bg-color);
    border-radius: calc(var(--custom-radius) + 4px) !important;
  }

  .column {
    display: flex;
    justify-content: space-between;
    margin-top: var(--console-margin);
    background-color: transparent !important;
  }

  .bottom-wrap {
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    height: 300px;
    padding: 20px;
    margin-top: var(--console-margin);
    background: var(--art-main-bg-color);

    h2 {
      margin-top: 10px;
      font-size: 20px;
      font-weight: 500;
    }

    p {
      margin-top: 5px;
      font-size: 14px;
      color: var(--art-gray-600);
    }

    .button-wrap {
      display: flex;
      flex-wrap: wrap;
      width: 600px;
      margin-top: 35px;

      .btn {
        display: flex;
        justify-content: space-between;
        width: 240px;
        height: 50px;
        padding: 0 15px;
        margin: 0 15px 15px 0;
        font-size: 14px;
        line-height: 50px;
        color: var(--art-gray-800);
        text-align: center;
        cursor: pointer;
        background: var(--art-bg-color);
        border-radius: calc(var(--custom-radius) / 2 + 2px) !important;
        transition: all 0.3s;

        &:hover {
          box-shadow: 0 5px 10px rgb(0 0 0 / 5%);
          transform: translateY(-4px);
        }
      }
    }
  }
}

.page-content {
  width: 100%;
  height: 100%;

  .user {
    .avatar {
      width: 40px;
      height: 40px;
      border-radius: 6px;
    }

    >div {
      margin-left: 10px;

      .user-name {
        font-weight: 500;
        color: var(--art-text-gray-800);
      }
    }
  }
}
</style>
